<template>
  <div class="get-token-container" :class="{ 'mobile-layout': isMobileDevice }">
    <!-- 移动端Logo区域 -->
    <div v-if="isMobileDevice" class="mobile-logo">
      <div class="logo-icon">
        <el-icon size="48"><Key /></el-icon>
      </div>
      <h1>获取Token</h1>
      <p>输入相关信息获取流量监控Token</p>
    </div>

    <el-card class="token-card" :class="{ 'mobile-card': isMobileDevice, 'desktop-card': !isMobileDevice }">
      <template #header v-if="!isMobileDevice">
        <div class="desktop-header">
          <div class="header-back">
            <el-button type="text" @click="goBack" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
          </div>
          <div class="header-content">
            <h2>获取Token</h2>
            <p>输入相关信息获取流量监控Token</p>
          </div>
          <div class="header-space"></div>
        </div>
      </template>
      
      <div v-if="isMobileDevice" class="mobile-form-header">
        <el-button type="text" @click="goBack" class="mobile-back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h3>Token获取</h3>
        <div class="header-space"></div>
      </div>

      <el-form
        ref="tokenFormRef"
        :model="tokenForm"
        :rules="tokenRules"
        :label-width="isMobileDevice ? 'auto' : '100px'"
        :label-position="isMobileDevice ? 'top' : 'right'"
        :size="isMobileDevice ? 'default' : 'large'"
        :class="{ 'mobile-form': isMobileDevice, 'desktop-form': !isMobileDevice }"
      >
        <FormField
          type="select"
          label="运营商"
          prop="operator"
          v-model="tokenForm.operator"
          placeholder="请选择运营商"
          :options="operatorOptions"
          :rules="tokenRules.operator"
        />
        
        <FormField
          type="input"
          label="手机号"
          prop="phone"
          v-model="tokenForm.phone"
          placeholder="请输入手机号"
          :rules="tokenRules.phone"
        />
        
        <FormField
          type="input"
          label="验证码"
          prop="code"
          v-model="tokenForm.code"
          placeholder="请输入验证码"
          :rules="tokenRules.code"
        />
        
        <FormField
          type="input"
          label="App ID"
          prop="appid"
          v-model="tokenForm.appid"
          placeholder="请输入App ID"
          :rules="tokenRules.appid"
        />

        <el-form-item class="submit-actions">
          <el-button
            type="primary"
            :class="{ 'mobile-submit-btn': isMobileDevice }"
            style="width: 100%"
            :loading="loading"
            @click="handleGetToken"
          >
            一键获取Token
          </el-button>
        </el-form-item>
      </el-form>

      <!-- Token结果显示 -->
      <div v-if="tokenResult" class="token-result" :class="{ 'mobile-result': isMobileDevice }">
        <el-divider content-position="center">获取结果</el-divider>
        
        <el-alert
          title="Token获取成功"
          type="success"
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <!-- 移动端结果显示 -->
        <div v-if="isMobileDevice" class="mobile-token-result">
          <div class="mobile-result-item">
            <div class="result-label">Token</div>
            <div class="token-display">
              <el-input
                v-model="tokenResult.token"
                readonly
                type="textarea"
                :rows="3"
                class="mobile-token-input"
              />
              <div class="mobile-token-actions">
                <el-button type="primary" size="small" @click="copyToken">
                  <el-icon><DocumentCopy /></el-icon>
                  复制Token
                </el-button>
                <el-button size="small" @click="selectAllToken">
                  <el-icon><Select /></el-icon>
                  全选
                </el-button>
                <el-button type="success" size="small" @click="exportToken('txt')">
                  <el-icon><Download /></el-icon>
                  导出TXT
                </el-button>
              </div>
            </div>
          </div>
          <div class="mobile-result-item">
            <div class="result-label">过期时间</div>
            <div class="result-value">{{ formatExpireTime(tokenResult.expires) }}</div>
          </div>
        </div>

        <!-- 桌面端结果显示 -->
        <el-descriptions v-else :column="1" border>
          <el-descriptions-item label="Token">
            <div class="token-display">
              <el-input
                v-model="tokenResult.token"
                readonly
                type="textarea"
                :rows="3"
                style="margin-bottom: 10px;"
              >
                <template #append>
                  <el-button @click="copyToken" :icon="DocumentCopy">复制</el-button>
                </template>
              </el-input>
              <div class="desktop-copy-actions">
                <el-button type="primary" size="small" @click="copyToken">
                  <el-icon><DocumentCopy /></el-icon>
                  一键复制Token
                </el-button>
                <el-button size="small" @click="selectAllToken">
                  <el-icon><Select /></el-icon>
                  全选Token
                </el-button>
                <el-dropdown @command="exportToken" trigger="click">
                  <el-button type="success" size="small">
                    <el-icon><Download /></el-icon>
                    导出文档
                    <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="txt">
                        <el-icon><Document /></el-icon>
                        导出为TXT文档
                      </el-dropdown-item>
                      <el-dropdown-item command="json">
                        <el-icon><Document /></el-icon>
                        导出为JSON文档
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="过期时间">
            {{ formatExpireTime(tokenResult.expires) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="result-actions" :class="{ 'mobile-actions': isMobileDevice }">
          <el-button 
            type="primary" 
            :class="{ 'mobile-action-btn': isMobileDevice }"
            @click="goToConfig"
          >
            去配置监控
          </el-button>
          <el-button 
            :class="{ 'mobile-action-btn': isMobileDevice }"
            @click="resetForm"
          >
            重新获取
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Key, ArrowLeft, DocumentCopy, Select, Download, ArrowDown, Document } from '@element-plus/icons-vue'
import { getToken } from '@/api/thirdParty'
import FormField from '@/components/FormField.vue'

const router = useRouter()

const tokenFormRef = ref()
const loading = ref(false)
const tokenResult = ref(null)

// 设备类型检测
const isMobileDevice = computed(() => {
  return window.innerWidth <= 768 || document.body.classList.contains('mobile-device')
})

const isDesktopDevice = computed(() => {
  return window.innerWidth > 768 || document.body.classList.contains('desktop-device', 'tablet-device')
})

const tokenForm = reactive({
  operator: '联通',
  phone: '',
  code: '',
  appid: ''
})

const operatorOptions = [
  { label: '联通', value: '联通' },
  { label: '移动', value: '移动' },
  { label: '电信', value: '电信' }
]

const tokenRules = {
  operator: [
    { required: true, message: '请选择运营商', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{4,6}$/, message: '验证码格式不正确', trigger: 'blur' }
  ],
  appid: [
    { required: true, message: '请输入App ID', trigger: 'blur' }
  ]
}

const handleGetToken = async () => {
  if (!tokenFormRef.value) return
  
  try {
    await tokenFormRef.value.validate()
    loading.value = true
    
    const response = await getToken(tokenForm)
    
    if (response.success) {
      tokenResult.value = response.data
      ElMessage.success('Token获取成功')
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('获取Token失败:', error)
    ElMessage.error(error.message || '获取Token失败')
  } finally {
    loading.value = false
  }
}

const copyToken = async () => {
  try {
    // 优先使用现代的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(tokenResult.value.token)
      ElMessage.success('Token已复制到剪贴板')
      return
    }
    
    // 降级到传统的 document.execCommand 方法
    const textArea = document.createElement('textarea')
    textArea.value = tokenResult.value.token
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    
    if (document.execCommand('copy')) {
      ElMessage.success('Token已复制到剪贴板')
    } else {
      throw new Error('execCommand failed')
    }
    
    document.body.removeChild(textArea)
  } catch (error) {
    console.error('复制失败:', error)
    // 最后的降级方案：显示手动复制提示
    ElMessage({
      message: '自动复制失败，请手动选择并复制Token文本',
      type: 'warning',
      duration: 5000
    })
  }
}

const selectAllToken = () => {
  try {
    // 查找页面中的token文本域（桌面端和移动端）
    const tokenTextarea = document.querySelector('.token-display textarea') || 
                         document.querySelector('.mobile-token-input textarea')
    
    if (tokenTextarea) {
      tokenTextarea.focus()
      tokenTextarea.select()
      
      // 检测设备类型显示不同的提示
      const isMobile = isMobileDevice.value
      const copyHint = isMobile ? '长按可复制文本' : '请按 Ctrl+C 复制'
      
      ElMessage({
        message: `Token文本已全选，${copyHint}`,
        type: 'info',
        duration: 3000
      })
    } else {
      throw new Error('无法找到Token文本框')
    }
  } catch (error) {
    console.error('选择Token失败:', error)
    ElMessage.warning('请手动选择Token文本')
  }
}

const exportToken = (format = 'txt') => {
  try {
    if (!tokenResult.value || !tokenResult.value.token) {
      ElMessage.warning('没有可导出的Token数据')
      return
    }

    // 生成文件名：日期+手机号码
    const now = new Date()
    const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '') // YYYYMMDD格式
    const phoneStr = tokenForm.phone ? tokenForm.phone.replace(/\D/g, '') : 'unknown' // 只保留数字
    const fileName = `${dateStr}_${phoneStr}_Token.${format}`

    let content, mimeType

    if (format === 'json') {
      // JSON格式导出
      const tokenData = {
        token: tokenResult.value.token,
        expires: tokenResult.value.expires,
        phone: tokenForm.phone,
        operator: tokenForm.operator,
        appId: tokenForm.appid || '',
        exportTime: new Date().toISOString(),
        exportTimeLocal: new Date().toLocaleString('zh-CN', {
          timeZone: 'Asia/Shanghai'
        })
      }
      content = JSON.stringify(tokenData, null, 2)
      mimeType = 'application/json;charset=utf-8'
    } else {
      // TXT格式导出
      content = `流量监控Token信息
====================

获取时间: ${formatExpireTime(Date.now())}
过期时间: ${formatExpireTime(tokenResult.value.expires)}
手机号码: ${tokenForm.phone}
运营商: ${tokenForm.operator}
App ID: ${tokenForm.appid || '未设置'}

Token:
${tokenResult.value.token}

====================
导出时间: ${new Date().toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai'
      })}
`
      mimeType = 'text/plain;charset=utf-8'
    }

    // 创建Blob对象
    const blob = new Blob([content], { type: mimeType })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.style.display = 'none'
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 清理URL对象
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(`Token文档已导出: ${fileName}`)
  } catch (error) {
    console.error('导出Token失败:', error)
    ElMessage.error('导出Token失败，请重试')
  }
}

const formatExpireTime = (timestamp) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai'
  })
}

const goToConfig = () => {
  // 跳转到配置页面（如果未登录会自动跳转到登录页面）
  router.push('/traffic-monitor')
}

const resetForm = () => {
  tokenResult.value = null
  tokenFormRef.value?.resetFields()
}

const goBack = () => {
  // 清除监控模式标记，允许用户正常导航
  sessionStorage.removeItem('isMonitorMode')
  router.back()
}

// 在组件挂载时清除监控模式标记
onMounted(() => {
  sessionStorage.removeItem('isMonitorMode')
})
</script>

<style scoped>
/* 基础容器样式 */
.get-token-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.get-token-container.mobile-layout {
  flex-direction: column;
  align-items: stretch;
  padding: 0;
  background: #f8f9fa;
}

/* 移动端Logo区域 */
.mobile-logo {
  text-align: center;
  padding: 40px 20px 30px 20px;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 100%;
  border-radius: 0 0 24px 24px;
  margin-bottom: 20px;
  flex-shrink: 0;
  order: -1; /* 确保在最顶部 */
}

.logo-icon {
  margin-bottom: 16px;
}

.mobile-logo h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.mobile-logo p {
  margin: 0;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 卡片样式 */
.token-card {
  width: 100%;
  max-width: 500px;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.token-card.mobile-card {
  margin: 0 16px 20px 16px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.token-card.desktop-card {
  width: 600px;
}

.token-card :deep(.el-card__header) {
  text-align: center;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.token-card h2 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 22px;
}

.token-card p {
  margin: 0;
  color: #6c757d;
  font-size: 14px;
}

/* 桌面端头部 */
.desktop-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-back,
.header-space {
  flex: 0 0 80px;
}

.header-content {
  flex: 1;
  text-align: center;
}

.back-btn {
  color: #667eea !important;
  font-size: 14px;
  padding: 8px 12px;
}

.back-btn:hover {
  background-color: rgba(102, 126, 234, 0.1);
}

/* 移动端表单头部 */
.mobile-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  margin-bottom: 24px;
}

.mobile-form-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  text-align: center;
}

.mobile-back-btn {
  color: #667eea !important;
  font-size: 16px;
  padding: 8px;
  flex: 0 0 auto;
}

.mobile-form-header .header-space {
  flex: 0 0 40px;
}

/* 表单样式 */
.mobile-form {
  padding: 0 4px;
}

.desktop-form {
  max-width: 500px;
  margin: 0 auto;
}

.submit-actions {
  margin-top: 24px;
}

.mobile-submit-btn {
  height: 48px !important;
  font-size: 16px !important;
  border-radius: 8px !important;
  font-weight: 600;
}

/* Token结果显示 */
.token-result {
  margin-top: 20px;
}

.token-result.mobile-result {
  margin-top: 24px;
}

.token-display {
  width: 100%;
}

.desktop-copy-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  margin-top: 8px;
}

/* 移动端结果显示 */
.mobile-token-result {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mobile-result-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #eee;
}

.result-label {
  font-size: 14px;
  font-weight: 600;
  color: #666;
  margin-bottom: 8px;
}

.result-value {
  font-size: 14px;
  color: #333;
  word-break: break-all;
}

.mobile-token-input {
  margin-bottom: 12px;
}

.mobile-token-actions {
  display: flex;
  gap: 6px;
  justify-content: center;
  flex-wrap: wrap;
}

.mobile-token-actions .el-button {
  flex: 1;
  min-width: 0;
  font-size: 12px;
}

/* 操作按钮 */
.result-actions {
  margin-top: 20px;
  text-align: center;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.result-actions.mobile-actions {
  flex-direction: column;
  gap: 12px;
  margin-top: 24px;
}

.mobile-action-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
}

/* 响应式优化 */
@media (max-width: 480px) {
  .get-token-container.mobile-layout {
    padding: 0;
    min-height: 100vh;
  }
  
  .mobile-logo {
    padding: 30px 20px 24px 20px;
    border-radius: 0 0 20px 20px;
    margin-bottom: 16px;
  }
  
  .mobile-logo h1 {
    font-size: 20px;
  }
  
  .token-card.mobile-card {
    margin: 0 12px 20px 12px;
  }
  
  .mobile-form-header h3 {
    font-size: 16px;
  }
  
  .mobile-result-item {
    padding: 12px;
  }
}

/* 键盘弹起时的适配 */
@media (max-height: 600px) {
  .mobile-logo {
    padding: 20px 20px 16px 20px;
  }
  
  .mobile-logo h1 {
    font-size: 18px;
  }
  
  .mobile-logo p {
    font-size: 12px;
  }
}

/* 横屏适配 */
@media (max-width: 768px) and (orientation: landscape) {
  .get-token-container.mobile-layout {
    flex-direction: row;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  .mobile-logo {
    display: none;
  }
  
  .token-card.mobile-card {
    margin: 0;
    max-width: 500px;
  }
}

/* 桌面端优化 */
@media (min-width: 769px) {
  .get-token-container:not(.mobile-layout) {
    padding: 40px 20px;
  }
  
  .token-card.desktop-card {
    width: 700px;
    max-width: 90vw;
  }
  
  .desktop-form {
    max-width: 600px;
  }
  
  .token-card h2 {
    font-size: 24px;
  }
  
  .result-actions {
    margin-top: 30px;
  }
}

/* 大屏桌面端 */
@media (min-width: 1200px) {
  .token-card.desktop-card {
    width: 800px;
  }
  
  .desktop-form {
    max-width: 700px;
  }
}

/* 超大屏幕 */
@media (min-width: 1600px) {
  .token-card.desktop-card {
    width: 900px;
  }
}

/* Element Plus 组件优化 */
.token-card :deep(.el-card__body) {
  padding: 24px;
}

.mobile-card :deep(.el-card__body) {
  padding: 20px;
}

/* 移动端输入框优化 */
.mobile-form :deep(.el-input__inner) {
  height: 48px !important;
  font-size: 16px !important;
  border-radius: 8px !important;
}

.mobile-form :deep(.el-select .el-input__inner) {
  height: 48px !important;
  font-size: 16px !important;
}

.mobile-form :deep(.el-textarea__inner) {
  font-size: 16px !important;
  border-radius: 8px !important;
}

/* 防止iOS自动缩放 */
@supports (-webkit-touch-callout: none) {
  .mobile-form :deep(.el-input__inner),
  .mobile-form :deep(.el-textarea__inner) {
    font-size: 16px !important;
  }
}
</style>
